package com.sinog.auth.config;

import com.sinog.auth.service.AccountUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @desc 自定义安全配置
 * @author zy
 * @date -
 */
@Slf4j
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${gkzx.azbj.clientWebPage}")
    private String defaultpage;
    @Autowired
    private AccountUserDetailService accountUserDetailService;
    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    /**
     * 初始化密码加密对象
     * @return BCryptPasswordEncoder BCryptPasswordEncoder
     */
    @Bean
    public BCryptPasswordEncoder myEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(WebSecurity web) {
        // 需要配置静态映射
        web.ignoring().antMatchers("/static/**","/webjars/**","/pro/api/**", "templates/errorMsg.ftl");
    }

    /**
     * 自定义认证规则
     * @param http http
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许所有用户访问"/"和"/home"
        http.csrf().disable().authorizeRequests()
            .antMatchers("/user/password","/user/info","/user/verifypwd","/pro/api/**","/upload/chrome/download",
                    "/getCaptcha","/azbj/user/getSjUserAll","/azbj/azbjgl/oldToNewMiddle","/errorMsg","/send","/errorMsgSx")
            .permitAll().anyRequest()
            //其他地址的访问均需验证权限
            .authenticated()
            //指定登录页是"/login"
            .and().formLogin().loginPage("/login").defaultSuccessUrl(defaultpage).permitAll()
            .failureHandler(myAuthenticationFailureHandler).permitAll()
            .and().logout().logoutSuccessUrl("/login").permitAll()
            .and().httpBasic().disable().cors();
        http.headers().frameOptions().disable();
        http.csrf().disable().sessionManagement().invalidSessionUrl("/login");
    }

    /**
     * 校验用户的账户密码是否正确
     * @param auth auth
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    private LoginAuthenticationProvider daoAuthenticationProvider() {
        //校验密码
        LoginAuthenticationProvider provider = new LoginAuthenticationProvider();
        // 设置userDetailsService
        provider.setUserDetailsService(accountUserDetailService);
        // 禁止隐藏用户未找到异常
        provider.setHideUserNotFoundExceptions(false);
        // 使用BCrypt进行密码的hash
        provider.setPasswordEncoder(myEncoder());
        return provider;
    }
}